import { useState } from "react";

function Cars() {
  const [cars, setCars] = useState([]);
  const [carYear, setCarYear] = useState(new Date().getFullYear());
  const [carMaker, setCarMaker] = useState("");
  const [carModel, setCarModel] = useState("");

  const handleAddCar = () => {
    const car = {
      year: carYear,
      maker: carMaker,
      model: carModel,
    };

    // 添加到cars
    setCars((c) => [...c, car]);
    // 清空
    setCarYear(new Date().getFullYear());
    setCarMaker("");
    setCarModel("");
  };

  const handleDeleteCar = (index) =>
    setCars((c) => c.filter((_, i) => i !== index));

  const handleCarYearChange = (e) => setCarYear((c) => e.target.value);
  const handleCarMakerChange = (e) => setCarMaker((c) => e.target.value);
  const handleCarModelChange = (e) => setCarModel((c) => e.target.value);

  const listItems = cars.map((car, index) => (
    <li key={index} onClick={() => handleDeleteCar(index)}>
      {car.year} {car.maker} {car.model}
    </li>
  ));

  return (
    <>
      <h2>List of Cars</h2>
      <ul>{listItems}</ul>
      <input
        type="number"
        value={carYear}
        onChange={handleCarYearChange}
      />{" "}
      <br />
      <input
        type="text"
        value={carMaker}
        onChange={handleCarMakerChange}
      />{" "}
      <br />
      <input
        type="text"
        value={carModel}
        onChange={handleCarModelChange}
      />{" "}
      <br />
      <button onClick={handleAddCar}>Add Car</button>
    </>
  );
}

export default Cars;
